<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Client\Logic\Detail;

use Hyperf\DbConnection\Db;


/**
 * 客户详情打标签.
 *
 * Class IndexLogic
 */
class PutTagLogic
{



    /**
     * 成员详情添加标签.
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle(array $params): array
    {

        // 查询客户已有标签
        $tagId = Db::table('client_tag_pivot')->where('client_id', $params['clientId'])->pluck('client_tag_id')->toArray();
        //传入的与已有的差集为新增
        $createIds = array_diff($params['tagIds'], $tagId);
        //已有的与传入的差集为删除
        $deleteIds = array_diff($tagId, $params['tagIds']);
        //事务处理
        Db::transaction(function () use ($params, $createIds, $deleteIds) {
            Db::table('client_tag_pivot')->where('client_id', $params['clientId'])->whereIn('client_tag_id', $deleteIds)->delete();
            foreach ($createIds as $key => $value) {
                Db::table('client_tag_pivot')->insert(['client_id' => $params['clientId'], 'client_tag_id' => $value, 'created_at' => date('Y-m-d H:i:s')]);
            }
        });
        return [];
    }
}
